#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "syntaxtree.h"
#include "syntax.tab.h"

NODE* child[10];


NODE* createNode(const char* type, int lineno, int num, union data_type* data) {
    NODE* p = (NODE*)malloc(sizeof(NODE));
    p->type = (char*)malloc(strlen(type));
    strcpy(p->type, type);
    p->lineno = -1;//标记为终结符
    if(!strcmp(type,"INT")) (p->data).type_int = data->type_int;
    else if (!strcmp(type,"FLOAT")) (p->data).type_float = data->type_float;
    else if (!strcmp(type, "TYPE")) {
        (p->data).type_type = (char*)malloc(strlen((char*)data));
        strcpy((p->data).type_type, (char*)data);
    }
    else if (!strcmp(type, "ID")) {
        (p->data).type_id = (char*)malloc(strlen((char*)data));
        strcpy((p->data).type_id, (char*)data);
    }
    else {
        p->lineno = lineno;//非终结符调整行号
    }
    p->num = num;
    for (int i = 0; i < num; i++) {
        if(child[i] != NULL) (p->child)[i] = child[i];
    }
    return p;
}

void output(NODE* node, int level) {
    if (node != NULL) {
        for (int i = 0; i < level; i++) {
            printf("  ");
        }
        if(!strcmp(node->type,"INT")) printf("%s: %d\n",node->type,(node->data).type_int);
        else if (!strcmp(node->type,"FLOAT")) printf("%s: %f\n",node->type,(node->data).type_float);
        else if (!strcmp(node->type,"TYPE")) printf("%s: %s\n",node->type,(node->data).type_type);
        else if (!strcmp(node->type,"ID")) printf("%s: %s\n",node->type,(node->data).type_id);
        else if (node->lineno!=-1) printf("%s (%d)\n",node->type,node->lineno);
        else printf("%s\n",node->type);
        level++;
        for (int i = 0; i < node->num; i++)
        {
            output((node->child)[i], level + 1);
        }

    }
}